#ifndef __TERRAIN_SERIALIZER_23_H__
#define __TERRAIN_SERIALIZER_23_H__

#include <cstdint>
#include <cstring>
#include <vector>
#include <unordered_map>
#include "Terrain/Region.hpp"
#include "Terrain/ITerrainSerializer.hpp"
#include "Terrain/TerrainChunk.h"
#include <mutex>
#include <map>
#include "concurrentqueue.h"
#include "Utils/Utils.h"
#include <functional>

namespace PocketSurvival
{
    // 支持原版2.3地形得序列化器
    class TerrainSerializer23 : public ITerrainSerializer
    {
    private:
        std::vector<Region *> m_regionCatchVector;
        moodycamel::ConcurrentQueue<Region *> m_regionQueue;
        std::unordered_map<int64_t, Region*> m_regionMap;
        std::mutex m_regionMapMutex;

    private:
        void createRegionCatch(uint8_t count);
        Region* getRegion(int32_t x, int32_t y);
        Region* getNoDataRegion();
        bool decompressChunkData(TerrainChunk *, const uint8_t *buffer, int32_t buffSize);
        int32_t compressChunkData(TerrainChunk *, uint8_t *buffer, int32_t buffSize);
    protected:
        void internalSaveRegion(Byte8Data key, Region *region, std::function<void(Region *)> callback);

    public:
        TerrainSerializer23();
        ~TerrainSerializer23();

        virtual bool loadChunk(TerrainChunk* ) override;
        virtual bool saveChunk(TerrainChunk* ) override;

        virtual void saveAllRegion() override;
        virtual void releaseAllRegion() override;
        virtual void saveAndReleaseAllRegion() override;
    };
    
}

#endif